<template>
  <a-card :bordered="false">
    <h3>评论管理</h3>
    <ContentFilter ref="filter" :type="5" :activeKey="activeKey" @onSearch="onSearch"></ContentFilter>
    <div style="position: relative;">
      <a-tabs v-model="activeKey" @change="tabChange">
        <a-tab-pane v-for="item in tabList" :tab="item.name" :key="item.status"> </a-tab-pane>
      </a-tabs>
      <template v-if="activeKey == 2">
        <a-popconfirm ok-text="确定" cancel-text="暂不" @confirm="handleBatchPass">
          <template slot="title">
            <p>确定通过评论吗？</p>
            <p>通过后，评论内容将对其他人可见</p>
          </template>
          <a-button class="batch-btn"  type="primary" :disabled="!selectedRows.length">
            批量通过
          </a-button>
        </a-popconfirm>
      </template>
    </div>
    <s-table
      ref="table"
      size="default"
      :rowKey="record => record.id"
      :columns="columns"
      :data="loadData"
      :pagination="paginationProps"
      :scroll="{ x: 1300 }"
      :rowSelection="activeKey == 2 ? rowSelection : null"
    >
      <span slot="userInfor" slot-scope="text,record"> {{ record.userNickname }}/{{ record.phone }}(社区ID：{{ record.communityId }}) </span>
      <span slot="failReason" slot-scope="text,record">
        <div>{{ record.failReason }}</div>
        <div style="color: #999;">{{ record.note }}</div>
      </span>
      <span slot="content" slot-scope="text,record">
        <div style="color: #999;" v-if="record.parentContent">被回复评论：<span v-html="record.parentContent"></span></div>
        <div><span v-if="record.parentContent">回复：</span><span v-html="record.content"></span></div>
      </span>
      <span slot="source" slot-scope="text,record">
        {{record.source | brand}}
      </span>
      
      <span slot="action" slot-scope="text,record">
        <a v-if="activeKey == 0" @click="handleDisableOrNopass(record, '1', 6)">禁用评论</a>
        <template v-if="activeKey == 2">
          <a-popconfirm ok-text="确定" cancel-text="暂不" @confirm="handlePassComment(record)">
            <template slot="title">
              <p>确定通过评论吗？</p>
              <p>通过后，评论内容将对其他人可见</p>
            </template>
            <a>通过</a><br />
          </a-popconfirm>
          <a @click="handleDisableOrNopass(record, '3', 5)">不通过</a>
        </template>
        <template v-if="activeKey == 1">
          <a-popconfirm ok-text="确定" cancel-text="暂不" @confirm="handleCommentEnable(record)">
            <template slot="title">
              <p>确定启用该条评论吗？</p>
              <p>通过后，评论内容将对其他人可见</p>
            </template>
            <a>启用评论</a>
          </a-popconfirm>
        </template>
      </span>
    </s-table>
    <DisableModal :title="title" :label="label" :visible.sync="disableVisible" :whyList="whyList" @onOk="onOk"></DisableModal>
  </a-card>
</template>
<script>
import { commentQuery, auditQuery, commentDisable, commentEnable, commentAudit, batchPass, commentCount } from '@/api/micromall/communityContent'
import { STable } from '@/views/box/components'
import ContentFilter from '../../components/ContentFilter'
import { enabledColumns, examineColumns, nopassColumns, disableColumns } from './commentList.js'
import DisableModal from '../../components/DisableModal'
import { whyPage } from '@/api/micromall/communityUser'
import { mapGetters } from 'vuex'
import { brandList } from '../../components/brandList.js'
const tabList = [
  {
    name: '已启用',
    status: '0'
  },
  {
    name: '待审核',
    status: '2'
  },
  {
    name: '已禁用',
    status: '1'
  },
  {
    name: '审核不通过',
    status: '3'
  }
]
export default {
  components: {
    ContentFilter,
    STable,
    DisableModal
  },
  data() {
    return {
      brandList,
      type: '',
      status: '',
      item: {},
      whyList: [],
      selectedRowKeys: [],
      selectedRows: [],
      disableVisible: false,
      // 0启用  1禁用 2待审核
      tabList,
      activeKey: this.$route.query.status || tabList[0].status,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      columns: enabledColumns,
      paginationProps: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
        // onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize)
      },
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const data = {
          status: this.activeKey == 3 ? null : this.activeKey,
          ...this.queryParam,
          current: parameter.pageNo,
          size: parameter.pageSize,
        }
        const listQuery = this.activeKey == 3 ? auditQuery : commentQuery
        return listQuery(data).then(res => {
          if (res.code === 200) {
            const { records, total, size, current } = res.data
            const currentRecords = records.map(e => {
              if (e.machineWord) {
                e.machineWord.split(',').forEach(i => {
                  e.content = e.content.replace(new RegExp(i,'g'), `<span style="color: red;">${i}</span>`),
                  e.parentContent = e.parentContent.replace(new RegExp(i,'g'), `<span style="color: red;">${i}</span>`)
                })
              }
              return e
            })
            console.log(currentRecords, 'currentRecords')
            
            const data = {
              page: {
                count: total,
                pageNo: current,
                pageSize: size,
                pages: Math.ceil(total / size)
              },
              data: currentRecords
            }
            return data
          } else {
            this.$message.error(res.msg)
            const data = {
              page: {
                count: 0,
                pageNo: 0,
                pages: 0
              },
              data: []
            }
            return data
          }
        })
      }
    }
  },
  created() {
    this.getCount()
  },
  computed: {
    title() {
      return this.activeKey == '0' ? '禁用内容/评论' : '评论审核'
    },
    label() {
      return this.activeKey=='0' ? '选择禁用原因（多选）' : '选择不通过原因（多选）'
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  filters: {
    brand(v) {
      const brandName = brandList.filter(e => e.weid == v).length ? brandList.filter(e => e.weid == v)[0].name + '微商城' : '/'
      return brandName
    }
  },
  mounted() {},
  watch: {
  },
  methods: {
     // 获取状态数量
    getCount() {
       commentCount({}).then(res => {
        if (res.code === 200) {
        const {disable, enable, unapproved} = res.data
          this.tabList[1].name = `待审核（${unapproved || 0}）`
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 批量审批
    handleBatchPass() {
      const data = {
        adminId: this.userInfo().id,
        adminName: this.userInfo().realname,
        ids: this.selectedRowKeys
      }
      batchPass(data).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
          this.selectedRowKeys = []
          this.selectedRows = []
          this.getCount()
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    // 禁用原因
    getWhyPage(type) {
      // 5:评论审核原因，6评论禁用原因
      const data = {
        type,
        status: 0
      }
      whyPage(data).then(res => {
        if (res.code === 200) {
          this.whyList = res.data.records
          this.type = type
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    ...mapGetters(['nickname', 'avatar', 'userInfo']),

    // 禁用/不通过
    handleDisableOrNopass(item, status, type) {
      // type 5:评论审核原因，6评论禁用原因 status: 1:禁用 3：不通过
      this.item = item
      this.status = status
      this.disableVisible = true
      if (this.type == type) return
      this.getWhyPage(type)
    },

    // 禁用/不通过弹窗确认
    onOk(v) {
      // status: 1:禁用 3：不通过
      if (this.status == 1) {
        this.getCommentDisable(v)
      } else {
        const { note, why } = v
        const data = {
          ...this.item,
          note,
          disableWhy: why.map(e => e.id).join(','),
          failReason: why.map(e => e.whyName).join(',')
        }
        this.getCommentAudit(data, '3')
      }
    },

    // 禁用
    getCommentDisable(v) {
      const { note, why } = v
      const data = {
        ...this.item,
        status: '1',
        adminId: this.userInfo().id,
        adminName: this.userInfo().realname,
        appraiseId: this.item.id,
        note: note,
        disableWhy: why.map(e => e.id).join(','),
        failReason: why.map(e => e.whyName).join(',')
      }
      commentDisable(data).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
          this.getCount()
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    // 启用
    handleCommentEnable(item) {
      const data = {
        ...item,
        status: '0',
        adminId: this.userInfo().id,
        adminName: this.userInfo().realname,
        appraiseId: item.id
      }
      commentEnable(data).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
          this.getCount()
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    // 审核通过
    handlePassComment(item) {
      this.getCommentAudit(item, '0')
    },

    // 审核通过/不通过
    getCommentAudit(item, status) {
      const data = {
        ...item,
        status,
        adminId: this.userInfo().id,
        adminName: this.userInfo().realname,
        appraiseId: item.id
      }
      commentAudit(data).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
          this.getCount()
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },

    tabChange(activeKey) {
      this.$nextTick(() => {
        this.activeKey = activeKey
        // 0启用  1禁用 2待审核
        switch (activeKey) {
          case '0':
            // 已启用
            this.columns = enabledColumns
            break
          case '2':
            // 待审核
            this.columns = examineColumns
            break
          case '1':
            // 已禁用
            this.columns = disableColumns
            break
          case '3':
            // 审核不通过
            this.columns = nopassColumns
            break
        }
        this.$refs.filter.reset()
      })
    },

    checkRoute(fromPath, routeArr) {
      for (let i = 0; i < routeArr.length; i++) {
        if (fromPath.includes(routeArr[i])) {
          return true
        }
      }
      return false
    },

    //查询
    onSearch(obj) {
      this.queryParam = obj
      this.$refs.table.refresh(true)
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-tabs-bar {
  margin-bottom: 0;
}

.img-wrapper {
  display: flex;

  .img-list {
    display: flex;
  }

  .img-text {
    line-height: 60px;
    color: #999;
  }
}

.img {
  display: block;
  margin: 0 2px;
  width: 60px;
  height: 60px;
  border: 1px dashed #f5f5f5;
  object-fit: scale-down;
  cursor: pointer;
}

.remarks {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  word-break: break-all; /* 追加这一行代码 */
  /* autoprefixer: off */
  -webkit-box-orient: vertical;
  /* autoprefixer: on */
}
.product {
  display: flex;
  overflow: hidden;
  .img {
    margin: 0;
  }
  .product-name {
    flex: 1;
    margin-left: 5px;
    width: 80px;
    text-align: left;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    word-break: break-all; /* 追加这一行代码 */
    /* autoprefixer: off */
    -webkit-box-orient: vertical;
    /* autoprefixer: on */
  }
}
.product-list {
  .product-item {
    line-height: 18px;
    text-align: left;
  }

  .product-num {
    cursor: pointer;
    text-align: left;
  }
}
.batch-btn {
  position: absolute;
  right: 0;
  bottom: 5px;
}
.image-video-wrapper {
  position: relative;
  width: 60px;
  height: 60px;
  margin: 0 auto;
  .img-num {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    line-height: 18px;
    text-align: center;
    font-size: 12px;
    color: #fff;
    background: rgba(0, 0, 0, 0.5);
  }
}
</style>
